<template>
  <div v-loading="loading">
    <el-row>
      <!-- <el-col style="text-align:left">
        <el-button
          type="success"
          @click="buttonClicks.addBtnClick"
        >添加</el-button> -->
      <!-- <el-button-group>
          <el-button
            type="primary"
            @click="buttonClicks.uploadExcelBtnClick"
          >上传Excel</el-button>
          <el-button
            type="primary"
            @click="buttonClicks.downloadExcelBtnClick"
          >下载Excel模板</el-button>
        </el-button-group> -->

    </el-row>

    <el-row class="marginTop10">
      <el-col :span="4">
        <el-date-picker
          v-model="tableDatas.exportYear"
          type="year"
          placeholder="选择年份"
          style="width:100%"
          @change="tableDatas.exportYearExcel"
          value-format="YYYY"
          :clearable="false"
        />
      </el-col>
      <el-col :span="1">
        <el-popover
          placement="bottom"
          trigger="click"
        >
          <template #reference>
            <el-button type="primary">导出年报表</el-button>
          </template>

        </el-popover>

      </el-col>
      <!-- <el-col :span="4">
        <el-select
          v-model="tableDatas.filters.hth"
          multiple
          placeholder="Select"
          style="width: 100%"
        >
          <el-option
            v-for="item in 5"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-col> -->

    </el-row>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
      :show-overflow-tooltip="true"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
      >
        <template #default="scope">
          <span :style="{ 'font-size':['UPDATETIME'].includes(column.prop) ? '10px':'14px'}">
            {{ tableDatas.getTextValueFromNumber(column.prop,scope.row[column.prop]) }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination>

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { h, onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import useMyXlsx from '@/hooks/useMyXlsx';
import { showWarning } from '@/hooks/useMyMessageBox';
import { dayjs, ElInput, ElOption, ElSelect, linkEmits } from 'element-plus';
import myAxios193 from '@/myAxios/myAxios193';
import VueCookie from 'vue-cookie';
import { read, utils } from 'xlsx';

export default {
  name: 'SybReport',
  setup () {
    let loading = ref(false);
    let dataTableDialog = ref(null);
    let deleteIds = ['3896'];
    let userid = VueCookie.get('userid');

    let formOptionTexts = {
      //产品 -1:其他 1: 马达 2:电机 3:驱动器 4:阀 5:导轨 6:机械手 7:磁板 8:驱动器+泵 9:电机+泵 10:电机+驱动器+泵 11:泵 12:电线
      productOptionText: '其他,马达,电机,驱动器,阀,导轨,机械手,磁板,驱动器+泵,电机+泵,电机+驱动器+泵,泵,电线',
      //事业部 1: 安信事业部 2:精密 3:液压传动事业部 4:自动化科技
      sybOptionText: '安信事业部,精密,液压传动事业部,自动化科技',
      //车长 4.2，6.2，6.8，9.6，13，17.5
      clOptionText: '4.2,6.2,6.8,9.6,13,17.5',
      //件数 1车，2车，3车
      ccOptionText: '1车,2车,3车',
      //快递类型 0:通宇 1:顺丰 2:申通 3:跨越 4:韵达
      kdTypeOptionText: '通宇,顺丰,申通,跨越,韵达',
    };
    let formOptions = {
      productOptions: formOptionTexts.productOptionText.split(',').map((text, index) => {
        return {
          value: index == 0 ? -1 : index,
          label: text
        };
      }),
      sybOptions: formOptionTexts.sybOptionText.split(',').map((text, index) => {
        return {
          value: index + 1,
          label: text
        };
      }),
      clOptions: formOptionTexts.clOptionText.split(',').map((text, index) => {
        return {
          value: text,
          label: text
        };
      }),
      //件数 1车，2车，3车
      ccOptions: formOptionTexts.ccOptionText.split(',').map((text, index) => {
        return {
          value: text,
          label: text
        };
      }),
      //类型 1:内销 2:外销
      typeOptions: [
        {
          value: 1,
          label: '内销'
        },
        {
          value: 2,
          label: '外销'
        },
      ],
      kdTypeOptions: formOptionTexts.kdTypeOptionText.split(',').map((text, index) => {
        return {
          value: index,
          label: text,
        };
      }),
    };

    let getTableDatas = function () {
      loading.value = true;

      let params = ``;
      myAxios.get('陈帅廷查询配送中心快递信息', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          res.forEach(item => {
            item.PERSON = {};
          });
          tableDatas.oritableData = [...res];

          ElMessage({
            showClose: true,
            type: 'success',
            message: '最新数据获取成功!'
          });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    let tableDatas = reactive({
      filters: {
        date: null,
        type: [1, 2],
        hth: [],
        khmc: '',
        lxr: '',
        syb: '',

        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableColumns: [
        {
          "prop": "TYPE",
          "label": "类型",
          "align": "center",
          "width": 60,
          // "filters": [
          //   {
          //     text: '内销',
          //     value: 1,
          //   },
          //   {
          //     text: '外销',
          //     value: 2,
          //   },
          // ],
          // "filterMethod": (value, row, column) => {
          //   return row['TYPE'] == value;
          // },
        },
        {
          "prop": "REDATE",
          "label": "出运日期",
          "align": "center",
          "width": 120,
        },
        {
          "prop": "PRODUCT",
          "label": "产品",
          "align": "center",
        },
        {
          "prop": "KD_TYPE",
          "label": "快递",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "KHMC",
          "label": "客户名称",
          "align": "center"
        },
        {
          "prop": "PRODUCT_TEXT",
          "label": "产品备注",
          "align": "center"
        },
        {
          "prop": "SYB",
          "label": "事业部",
          "align": "center",
          "width": 130,
        },
        {
          "prop": "CAR_LENGTH",
          "label": "车长",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "CAR_COUNT",
          "label": "件数",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "HTH",
          "label": "合同号",
          "align": "center"
        },
        {
          "prop": "ADDRESS",
          "label": "地址",
          "align": "center"
        },
        {
          "prop": "CONNECT_WAY",
          "label": "联系人",
          "align": "center"
        },
        {
          "prop": "WEIGHT",
          "label": "重量",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "YS_COST",
          "label": "运输费",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "PS_COST",
          "label": "配送费",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "SUM_COST",
          "label": "总费用",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "YWY",
          "label": "业务员",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "UPDATETIME",
          "label": "更新时间",
          "align": "center",
          "width": 130,
        },
        {
          "prop": "operate",
          "label": "操作",
          "align": "center",
          "width": 170,
        },
      ],
      getTextValueFromNumber: function (key, value) {
        if (key == 'PRODUCT') {
          let productOption = formOptions.productOptions.find(option => option.value == value);
          if (productOption)
            return productOption.label;
          else
            return '';
        }
        else if (key == 'SYB') {
          let sybOption = formOptions.sybOptions.find(option => option.value == value);
          if (sybOption)
            return sybOption.label;
          else
            return '';
        }
        else if (key == 'TYPE') {
          let typeOption = formOptions.typeOptions.find(option => option.value == value);
          if (typeOption)
            return typeOption.label;
          else
            return '';
        }
        else if (key == 'KD_TYPE') {
          let typeOption = formOptions.kdTypeOptions.find(option => option.value == value);
          if (typeOption)
            return typeOption.label;
          else
            return '';
        }
        else {
          return value;
        }
      },
      getNumberValueFromText: function (key, text) {
        if (key == 'PRODUCT') {
          let productOption = formOptions.productOptions.find(option => option.label == text);
          if (productOption)
            return productOption.value;
          else
            return -2;
        }
        else if (key == 'SYB') {
          let sybOption = formOptions.sybOptions.find(option => option.label == text);
          if (sybOption)
            return sybOption.value;
          else
            return -2;
        }
        else if (key == 'TYPE') {
          let typeOption = formOptions.typeOptions.find(option => option.label == text);
          if (typeOption)
            return typeOption.label;
          else
            return -2;
        }
        else if (key == 'KD_TYPE') {
          let typeOption = formOptions.kdTypeOptions.find(option => option.label == text);
          if (typeOption)
            return typeOption.value;
          else
            return -2;
        }
        else {
          return text;
        }
      },
      oritableData: [],
      tableDatasAfterFilter: computed(() => {
        let fData = [...tableDatas.oritableData];
        if (tableDatas.filters.type) {
          let type = tableDatas.filters.type;
          fData = fData.filter(item => type.includes(item.TYPE));
        }

        if (tableDatas.filters.date) {
          let date = tableDatas.filters.date;
          fData = fData.filter(item => item.REDATE >= date[0] && item.REDATE <= date[1]);
        }

        if (tableDatas.filters.khmc) {
          let khmc = tableDatas.filters.khmc;
          fData = fData.filter(item => {
            if (item.KHMC) {
              return item.KHMC.includes(khmc);
            }
            else {
              return false;
            }
          });
        }

        if (tableDatas.filters.lxr) {
          let lxr = tableDatas.filters.lxr;
          fData = fData.filter(item => {
            if (item.CONNECT_WAY) {
              return item.CONNECT_WAY.includes(lxr);
            }
            else {
              return false;
            }
          });
        }

        if (tableDatas.filters.syb) {
          let syb = tableDatas.filters.syb;
          fData = fData.filter(item => {
            if (item.SYB) {

              return tableDatas.getTextValueFromNumber('SYB', item.SYB).includes(syb);
            }
            else {
              return false;
            }
          });
        }


        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;

        fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),
      exportYear: '',
      exportYearExcel: function (e) {
        console.log('e :>> ', e);
        myAxios.get('陈帅廷查询配送中心年报表', `${tableDatas.exportYear}`).then(res => {
          console.log('res :>> ', res);
          if (res instanceof Array) {
            let data = [];
            res.forEach(item => {
              let newItem = { ...item };
              Object.keys(newItem).forEach(key => {
                newItem[key] = tableDatas.getTextValueFromNumber(key, newItem[key]);
              });
              data.push(newItem);
            });
            let xlsx = useMyXlsx();

            let replaceObj = {
              'SYB': '事业部',
              'TYPE': '内/外销',
              'YEAR': '年份',
              'AVG_SUM': '平均',
              'COUNT': '数量',
            };
            let hideColumns = ['SYB1', 'TYPE1'];
            let exportOption = {
              titles: replaceObj,
              header: [],
              hideColumns: hideColumns,
            };
            let keys = Object.keys(data[0]);
            for (let i = 0; i < keys.length; i++) {
              let key = keys[i];
              //不需要隐藏,而且没有初始列名的key,直接用key当列名
              if (!hideColumns.includes(key) && !exportOption.titles[key]) {
                exportOption.titles[key] = key;
              }
              exportOption.header.push(key);
            }
            let now = tableDatas.exportYear + '年报表';
            xlsx.exportDatas(data, exportOption, now + '.xlsx');
          }
          else {
            showWarning('数据查询失败res' + res);
          }
        }).catch(err => {
          showWarning('导出失败err' + err);
        });
      },
    });

    return {
      loading,
      dataTableDialog,
      deleteIds, userid,
      tableDatas,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

